<template>
    <div class="view">
        <nav-bar title="设置" :fixed="false" :shadow="true">
            <div class="back" slot="left" @click="back">
                <i class="iconfont icon-fanhui"></i>
            </div>
        </nav-bar>
        <div class="setting-wrap">
            <cube-scroll>
                <list-cell title="通知设置" @click="toPage('settingNotification')"></list-cell>
                <list-cell title="个性设置" @click="toPage('settingSoundAndShock')"></list-cell>
                <!--                <list-cell title="隐私设置"></list-cell>-->
                <list-cell title="账户与安全" :showBorder="false" style="margin-top: 10px;" @click="toPage('accountAndSecurity')"></list-cell>
                <list-cell title="关于心相依" style="margin-top: 10px;" @click="toPage('about')"></list-cell>
                <list-cell title="APP下载" @click="toPage('appDownload')" v-if="!device.status"></list-cell>
                <list-cell title="联系我们" :showBorder="false"></list-cell>

                <list-cell title="清除缓存" :showArrow="false" :showRightSlot="true" style="margin-top: 10px;" @click="clearCache">
                    <span class="cache-total" slot="rightSlot">{{cacheTotal}}</span>
                </list-cell>
                <template v-if="device.status && !isIos">
                    <list-cell title="检测版本更新" :showBorder="false" @click="testUpdate">
                        <span class="has-new-app" v-if="isAppUpdate" slot="rightSlot">新版本</span>
                    </list-cell>
                </template>
                <div class="exit" @click="exit">
                    退出账户
                </div>
            </cube-scroll>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Vue, Watch} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";

    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import CommonUnit from "@/unit/CommonUnit";
    import Heart from "@/unit/Heart";
    import UserEntity from "@/entity/UserEntity";
    import {clearDataCache, exitUser} from "@/store/dispatches";
    import {deviceReady} from "@/store/dispatches";

    import ListCell from "@/components/aui/ListCell.vue";
    import NavBar from "@/components/aui/NavBar.vue";

    @Component({
        components: {
            NavBar, ListCell
        }
    })
    export default class Setting extends Scene {

        private cacheTotal: string = "0KB";
        private clearStatus: boolean = true;
        private isIos: boolean = CommonUnit.deviceType().isiOS;

        @State("DeviceStore")
        private device: any;

        @State("UserStore")
        private user!: InterfaceUser;

        @Action("sendMessage")
        private socketSendMessage!: Function;

        @State("DataCacheStore")
        public dataCache!: any;

        private created() {
            this.getCacheTotal();
        }

        private get isAppUpdate(): boolean {
            if (this.device.status) {
                if (Number(this.device.netVersionCode) > Number(this.device.versionCode)) {
                    return true;
                }
                return false;
            }
            return false;
        }

        private getCacheTotal(): void {
            let cacheTotalNumber = 0;
            const webCacheByte = JSON.stringify(this.dataCache).replace(/[\u0391-\uFFE5]/g, "aa").length;
            cacheTotalNumber = cacheTotalNumber + webCacheByte;
            if (this.device.status) {
                cache.getCacheSize((res: any) => {
                    cacheTotalNumber = cacheTotalNumber + res.fileByte;
                    this.cacheTotal = CommonUnit.converSize(cacheTotalNumber);
                });
            }
            this.cacheTotal = CommonUnit.converSize(cacheTotalNumber);
        }

        private clearCache(): void {
            if (this.clearStatus) {
                this.clearStatus = false;
                clearDataCache();
                if (this.device.status) {
                    cache.deleteFileCache((res: any) => {
                        this.clearComplete();
                    }, (error: any) => {
                        console.log(error);
                        this.clearComplete();
                    });
                } else {
                    this.clearComplete();
                }
            }
        }

        private clearComplete(): void {
            this.getCacheTotal();
            (<any> this).$createToast({
                txt: "成功清理系统缓存",
                type: "txt",
                time: 1300,
                onTimeout: () => {
                    this.clearStatus = true;
                }
            }).show();
        }

        private back(): void {
            this.navigateBack();
        }

        private exit(): void {
            (<any> this).$createDialog({
                type: "confirm",
                title: "确认退出",
                content: "退出账号后，将接受不到心仪的异性发来的消息哦。",
                confirmBtn: {
                    text: "退出",
                    active: true,
                    disabled: false,
                    href: "javascript:;"
                },
                cancelBtn: {
                    text: "取消",
                    active: false,
                    disabled: false,
                    href: "javascript:;"
                },
                onConfirm: () => {
                    const toast = (<any> this).$createToast({
                        time: 0,
                        txt: "正在退出账户",
                        mask: true,
                    }).show();
                    try {
                        Http.get(this.api.logout, {}, {token: this.user.token}).finally(() => {
                            if (this.device.status) {
                                cordova.plugins.notification.badge.clear();
                            }
                            setTimeout(() => {
                                this.socketSendMessage(JSON.stringify({type: "unbind"}));
                                clearDataCache();
                                exitUser();
                                this.navigateLoginPage();
                                toast.hide();
                                localStorage.setItem("reloadTime", "0");
                            }, 400);

                        });
                    } catch (e) {
                        this.socketSendMessage(JSON.stringify({type: "unbind"}));
                        exitUser();
                        this.navigateLoginPage();
                        toast.hide();
                    }

                },
            }).show();
        }

        private testUpdate(): void {
            AppUpdate.checkAppUpdate((e: any) => {
                this.updateAppCb(e);
            }, (e: any) => {
                this.updateAppCb(e);
            }, this.api.appVersion);
        }

        private toPage(name: string) {
            this.navigateTo({
                name: name
            });
        }

        private updateAppCb(res: any) {
            let option: any = {
                type: "error",
                txt: "未知错误"
            };
            if (res.hasOwnProperty("code")) {
                if (res.code !== 201) {
                    switch (res.code) {
                        case 202:
                            option.type = "correct";
                            option.txt = "当前已经是最新版本了,软件不需要更新";
                            break;
                        case 203:
                            option.type = "warn";
                            option.txt = "软件正在更新";
                            break;
                        case 301:
                            option.type = "error";
                            option.txt = "版本文件解析错误";
                            break;
                        case 302:
                            option.type = "error";
                            option.txt = "版本文件对比错误";
                            break;
                        case 404:
                            option.type = "error";
                            option.txt = "版本文件未找到";
                            break;
                        case 405:
                            option.type = "error";
                            option.txt = "网络出错，请确认网络";
                            break;
                        case 601:
                            option.type = "error";
                            option.txt = "网络出错，请确认网络";
                            break;
                        default:
                            option.type = "error";
                            option.txt = "未知错误";
                    }
                    (<any> this).$createToast({
                        ...option,
                        time: 2000,
                    }).show();
                }
            }
        }
    }
</script>

<style scoped lang="stylus">
    .view
        height 100vh;
        width 100vw;
        background $theme-page-common-background-color;

        .setting-wrap
            width 100vw;
            height calc(100vh - var(--safe-area-inset-top) - 44px);
            position relative;
            border-top 1px solid rgba(200, 199, 204, .1);

            .exit
                height 40px
                margin 30px 20px 10px;
                justify-content center;
                align-items center;
                display flex;
                background $theme-common-gradient;
                border-radius 20px;
                color #fff;

    .cache-total
        color #999;

    .has-new-app
        font-size 10px;
        color #fff;
        background $theme-common-color;
        padding 4px 10px;
        border-radius 20px;
</style>
